<script setup lang="tsx">
import { restPasswordApi, phoneApi } from '@/api/login'
import { getTypeListApi } from "@/api/common/index"
import type { FormInstance, FormRules } from 'element-plus'
import { tenantApi } from '@/api/login'
import { Form, FormSchema } from '@/components/Form'
import { onActivated, reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { useRouter } from 'vue-router';
import { ElButton, ElCheckbox, ElInput, ElLink, ElMessage, configProviderContextKey } from 'element-plus'
import UpLoadImage from "@/views/Components/UpLoadImage.vue"
import UpLoadImages from "@/views/Components/UpLoadImages.vue"
import { useAppStoreWithOut } from '@/store/modules/app'
import { useStorage } from '@/hooks/web/useStorage'
import { UserType } from '@/api/login/types'
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const route = useRouter();
const loading = ref(false);
const code_text = ref("获取验证码");
const code_disabled = ref(false);
const code_loading = ref(false);
const code_timer = ref<number | null | undefined>();
const loadingAdd = ref(false)
const emit = defineEmits(['to-login'])
const { formRegister, formMethods } = useForm()
const { getElFormExpose, getFormData } = formMethods
const { t } = useI18n()
const { required } = useValidator()
// const rules = {
//   companyName: [
//     { required: true, message: '请输入企业名称', trigger: 'blur' },
//   ],
//   contactUserName: [
//     { required: true, message: '请输入企业联系人', trigger: 'blur' },
//   ],
//   username: [
//     { required: true, message: '请输入企业联系人手机号', trigger: 'blur' },
//   ],
//   password: [
//     { required: true, message: '请输入密码', trigger: 'blur' },
//   ],
//   check_password: [
//     { required: true, message: '请再次输入密码', trigger: 'blur' },
//   ],
//   code: [
//     { required: true, message: '请输入验证码', trigger: 'blur', },
//   ],
// }
const remember = ref(true)
const schema = reactive<FormSchema[]>([
  {
    field: 'Login',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <div>
            <h2 class="login-text2  w-[100%]">香城英才网</h2>
            {/* <h2 class="login-text3  w-[100%]">Human Resources Management System</h2> */}
          </div>
        }
      }
    }
  },
  {
    field: 'title',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return <h2 class="text-2xl font-bold  w-[100%]">{t('login.register')}</h2>
        }
      }
    }
  },
  {
    field: 'companyName',
    label: "",
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: "请输入企业名称"
    }
  },
  {
    field: 'contactUserName',
    label: "",
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: "请输入企业联系人"
    }
  },
  // {
  //   field: 'contactPhone',
  //   label: "",
  //   value: '',
  //   component: 'Input',
  //   colProps: {
  //     span: 24
  //   },
  //   componentProps: {
  //     placeholder: "请输入企业联系人电话"
  //   }
  // },
  {
    field: 'username',
    label: "",
    value: '',
    component: 'Input',
    colProps: {
      span: 24
    },
    componentProps: {
      placeholder: "请输入企业联系人电话"
    }
  },
  // {
  //   field: 'password',
  //   label: "",
  //   value: '',
  //   component: 'Input',
  //   colProps: {
  //     span: 24
  //   },
  //   formItemProps: {
  //     slots: {
  //       default: (data: any) => {
  //         return (
  //           <>
  //             <div class="flex w-[100%] phone_code_phone" >
  //               <el-form class="demo-ruleForm w-[100%]">
  //                 <el-form-item prop="code" >
  //                   <ElInput placeholder='请输入验证码' v-model={data.code} type='number' ></ElInput></el-form-item>
  //               </el-form>
  //               <div class="phone_code_span" onClick={getCode}>{code_text.value}</div>
  //             </div>
  //           </>
  //         )
  //       }
  //     }
  //   }
  // },
  {
    field: 'password',
    label: "",
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: false,
      placeholder: "请输入用户密码"
    }
  },
  {
    field: 'check_password',
    label: "",
    value: '',
    component: 'InputPassword',
    colProps: {
      span: 24
    },
    componentProps: {
      style: {
        width: '100%'
      },
      strength: false,
      placeholder: "请再次输入密码"
    }
  },
  {
    field: 'tool',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex  items-center w-[100%]">
                <ElCheckbox size="small" v-model={remember.value}>同意</ElCheckbox><span style="color:#2F6CBC;font-size:12px;cursor:pointer;" onClick={goShow}>《用户注册协议》</span>
              </div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'register',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="w-[100%]">
                <ElButton
                  type="primary"
                  class="w-[100%]"
                  loading={loading.value}
                  onClick={loginRegister}
                >
                  {t('login.register')}
                </ElButton>
              </div>
              <div class="w-[100%] mt-15px flex justify-center items-center">
                <ElLink type="primary" underline={false} onClick={toLogin}>已有账号?去登录</ElLink>
              </div>
            </>
          )
        }
      }
    }
  }
])
const toLogin = () => {
  emit('to-login')
}
const loginRegister = async () => {
  const formRef = await getElFormExpose()
  const formData = await getFormData()
  if (!remember.value) {
    ElMessage.error("用户注册协议!")
    return
  }
  formRef?.validate(async (valid) => {
    if (valid) {
      let params = {
        contactUserName: formData.contactUserName,
        contactPhone: formData.username,
        companyName: formData.companyName,
        username: formData.username,
        password: formData.password,
      }
      await tenantApi(params).then((res: any) => {
        ElMessage.success(res.msg)
        loading.value = false
        toLogin()
      }).catch((res: any) => {
        console.log(res);
        loading.value = false
        ElMessage.error(res.msg)
      })
    }
  })
}

const goShow = () => {
  console.log("服务条款");
  let { href }: any = route.resolve({
    path: '/service'
  })
  console.log(href);
  window.open(href, '_blank')
}
const state = reactive({
  readonly: true,
  options1: [] as any,
  options2: [] as any,
  options3: [] as any,
  ruleForm: {} as any,
  upLoadImage: {
    url: "",
    tip: "注意:建议尺寸：120*120像素图片大小不超过2M，支持jpg、jpeg、png格式",
    actionUrl: "/api/oss/upload",
    headers: {
      "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
      "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
    }
  },
  upLoadImages: {
    tip: "注意:最多上传10张，单张图片大小不超过2M，支持jpg、jpeg、png格式",
    urls: [],
    ossIds: "",
    limit: 10,
    actionUrl: "/api/oss/upload",
    headers: {
      "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
      "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
    }
  }
})


const uploadImageClick = (value: any) => {
  state.ruleForm.companyLogoId = value
  console.log("单图片上传", state.ruleForm.companyLogoId);
}
const uploadImageClicks = (value: any) => {
  state.ruleForm.businessLicenseId = value
  console.log("多图片上传", state.ruleForm.businessLicenseId);
}
interface RuleForm {
  companyLogoId: string
  businessLicenseId: string[]
  companyName: string
  contactPhone: string
  contactEmail: string
  username: string
  password: string
  contactUserName: string
  code: string
}


var checkData = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("密码不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};
var checkusername = (rule, value, callback) => {
  if (value) {
    if (/[\u4E00-\u9FA5]/g.test(value)) {
      callback(new Error("管理员账号不能输入汉字!"));
    } else {
      callback();
    }
  }
  callback();
};
var checkEmail = (rule, value, callback) => {
  const regEmail = /^\w+@\w+(\.\w+)+$/
  if (regEmail.test(value)) {
    // 合法邮箱
    return callback()
  }
  callback(new Error('请输入合法邮箱'))
}

const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
  contactUserName: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  companyLogoId: [{ required: true, message: '请上传公司logo', trigger: 'blur' }],
  businessLicenseId: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  companyName: [
    { required: true, message: '请填写公司名称', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
  ],
  contactEmail: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: checkEmail, trigger: "blur" },
  ],
  username: [
    { required: true, message: '请填写管理员账号', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkusername, trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: '请填写联系电话', trigger: 'blur' },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的电话",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { min: 1, max: 50, message: '不超过50个字符', trigger: 'blur' },
    { validator: checkData, trigger: "blur" },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur', },
  ],

})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!remember.value) {
    ElMessage.error("用户注册协议!")
    return
  }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      tenantApi(state.ruleForm).then((res: any) => {
        ElMessage.success(res.msg)
        loading.value = false
        toLogin()
      }).catch((res: any) => {
        console.log(res);
        loading.value = false
        ElMessage.error(res.msg)
      })
      console.log('submit!')
    } else {
      console.log('error submit!', fields)
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 字典
const getTypeListApi_ = (params) => {
  getTypeListApi(params).then((res: any) => {
    if (params == "company_type") {
      console.log("公司类别：", res);
      state.options1 = res.data
    } else if (params == "company_size") {
      console.log("规模：", res);
      state.options2 = res.data
    } else if (params == "company_industry") {
      console.log("性质：", res);
      state.options3 = res.data
    }

  })
}
getTypeListApi_("company_type")
getTypeListApi_("company_size")
getTypeListApi_("company_industry")
// onActivated(() => {

// })
function handlerIptClick() {
  state.readonly = false;
}


// --------------------------------------------------验证码校验
const getCode = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validateField("contactPhone", (valid: any) => {
    if (valid) {
      if (code_text.value == "重新获取" || code_text.value == "获取验证码") {
        phoneApi_()
        countdown();
      } else {
        return
      }
    }
  });
};

/** 倒计时 */
const countdown = () => {
  let second = 60; // 默认时间
  code_loading.value = false; // 取消加载
  // code_disabled.value = true; // 禁用按钮
  code_text.value = `${second}秒`; // 按钮文本
  // 判断是否存在定时器，存在则先清除
  if (code_timer.value) {
    clearInterval(code_timer.value);
  }
  // 开启定时器
  code_timer.value = Number(
    setInterval(() => {
      second--;
      code_text.value = `${second}秒`; // 按钮文本
      if (second <= 0) {
        code_text.value = `重新获取`; // 按钮文本
        // code_disabled.value = false; // 启用按钮
        clearInterval(code_timer.value as number); // 清除倒计时
      }
    }, 1000)
  );
};
// 获取手机验证码
const phoneApi_ = async () => {

  let params = {
    phonenumber: state.ruleForm.contactPhone
  }
  await phoneApi(params).then((res: any) => {
    console.log(res);
    ElMessage.success(res.msg)
  }).catch((res: any) => {
    ElMessage.error(res.msg)
  })
}
</script>

<template>
  <div>
    <h2 class="login-text2  w-[100%] " style="">香城英才网</h2>
    <h2 class="text-2xl font-bold  w-[100%]" style="margin: 16px 0;">注册</h2>
    <div class="" style="height: 50vh;overflow-y: auto;">
      <el-form ref="ruleFormRef" :model="state.ruleForm" :rules="rules" label-position="left" label-width="120px"
        class="demo-ruleForm" status-icon>
        <el-form-item label="公司logo" prop="companyLogoId">
          <UpLoadImage :data="state.upLoadImage" @uploadImageClick="uploadImageClick" />
        </el-form-item>
        <el-form-item label="营业执照" prop="businessLicenseId">
          <UpLoadImages :data="state.upLoadImages" @uploadImageClick="uploadImageClicks" />
        </el-form-item>
        <div class="business_content_main">
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="state.ruleForm.companyName" placeholder="请输入公司名称" />
          </el-form-item>
          <el-form-item label="公司性质" prop="">
            <el-select v-model="state.ruleForm.companyType" class="m-2" placeholder="请选择公司性质" style="width: 100%;">
              <el-option v-for="item in state.options1" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="公司规模" prop="">
            <el-select v-model="state.ruleForm.companySize" class="m-2" placeholder="请选择公司规模" style="width: 100%;">
              <el-option v-for="item in state.options2" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属行业" prop="">
            <el-select v-model="state.ruleForm.companyIndustry" class="m-2" placeholder="请选择所属行业" style="width: 100%;">
              <el-option v-for="item in state.options3" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="state.ruleForm.contactPhone" placeholder="请输入联系电话" @click='handlerIptClick'
              :readonly="state.readonly" />
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <div class="flex w-[100%] phone_code_phone">
              <el-input placeholder='请输入验证码' v-model="state.ruleForm.code" type='number' />
              <div class="phone_code_span" @click="getCode(ruleFormRef)">{{ code_text }}</div>
            </div>
          </el-form-item>

          <el-form-item label="管理员账号" prop="username">
            <el-input v-model="state.ruleForm.username" placeholder="请输入管理员账号" @click='handlerIptClick'
              :readonly="state.readonly" />
          </el-form-item>
          <el-form-item label="管理员密码" prop="password">
            <el-input v-model="state.ruleForm.password" type="password" show-password placeholder="请输入管理员密码" />
          </el-form-item>
          <el-form-item label="邮箱地址" prop="contactEmail">
            <el-input v-model="state.ruleForm.contactEmail" placeholder="请输入邮箱地址" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactUserName">
            <el-input v-model="state.ruleForm.contactUserName" placeholder="请输入联系人名称" />
          </el-form-item>
        </div>
        <el-form-item label="公司地址" prop="address">
          <el-input v-model="state.ruleForm.address" placeholder="请输入公司地址" />
        </el-form-item>
        <!-- <div class="flex jcsc aic">
        
        <el-form-item label="手机号验证" prop="username">
          <el-input v-model="state.ruleForm.username" placeholder="请输入验证码" style="width: 120px;" />
          <ElButton type="primary" @click="getCode()" style="width: 90px;margin-left: 16px;">{{ code_text }}</ElButton>
        </el-form-item>
      </div> -->
        <el-form-item label="公司简介" prop="intro">
          <el-input style="width: 100%;" v-model="state.ruleForm.intro" :autosize="{ minRows: 2 }" type="textarea"
            maxlength="500" show-word-limit placeholder="请输入公司简介" />
        </el-form-item>
      </el-form>
    </div>
    <div class="" style="margin: 16px 0;">
      <ElCheckbox size="small" v-model="remember">同意</ElCheckbox><span
        style="color:#2F6CBC;font-size:12px;cursor:pointer;" @click="goShow">《用户注册协议》</span>
    </div>
    <div class="flex">
      <div class="w-[100%]">
        <ElButton type="primary" class="w-[100%]" :loading="loading" @click="submitForm(ruleFormRef)">
          注册
        </ElButton>
      </div>

    </div>
    <div class="w-[100%] mt-15px flex justify-center items-center" style="margin: 16px 0;">
      <ElLink type="primary" :underline="false" @click="toLogin">已有账号?去登录</ElLink>
    </div>
  </div>

  <!-- <Form :schema="schema" :rules="rules" label-position="top" hide-required-asterisk size="large"
    class="dark:(border-1 border-[var(--el-border-color)] border-solid)" @register="formRegister" /> -->
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}

.imagelogo {
  width: 90px;
  height: 90px;
}

.el-image {
  width: 128px;
  height: 128px;
}
</style>
